package com.jzo2o.knife4j.filter;

import com.jzo2o.common.utils.IoUtils;
import com.jzo2o.knife4j.response.SwaggerTransformServletResponse;
import com.jzo2o.knife4j.utils.ResponseWrapper;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Swagger文档过滤器，用于拦截Swagger接口文档请求并转换响应格式
 */
@Component // 注册为Spring Bean
public class SwaggerFilter implements Filter {

    /**
     * 执行过滤逻辑：仅拦截Swagger的API文档请求，转换其响应格式
     *
     * @param servletRequest  请求对象
     * @param servletResponse 响应对象
     * @param filterChain     过滤器链
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 判断是否为Swagger的API文档请求（/v2/api-docs）
        if (request.getRequestURI().contains("/v2/api-docs")) {
            // 包装响应对象以获取原始Swagger文档数据
            ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
            // 继续执行过滤器链，获取原始响应数据
            filterChain.doFilter(servletRequest, responseWrapper);
            // 转换Swagger文档的响应格式（统一包装为通用响应结构）
            byte[] transformedData = SwaggerTransformServletResponse.getBody(responseWrapper.getResponseData());
            // 将转换后的数据写入响应流
            IoUtils.write(servletResponse.getOutputStream(), false, transformedData);
        } else {
            // 非Swagger文档请求，直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
